import { Injectable, OnApplicationBootstrap } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { GlobalConfigAdminUpdateDto, PresetSegmentFreqItem, TargetItem } from './global-config.dto';
import { GlobalConfigModel } from './global-config.model';
import { RedisService } from "@liaoliaots/nestjs-redis";
import { RedisNamespace } from "@/common/config/config.interface";
import { Redis } from "ioredis";

interface GlobalConfig {
  sensitive: string;
  targets: TargetItem[];
  presetSegmentFreq: PresetSegmentFreqItem[];
}

@Injectable()
export class GlobalConfigService implements OnApplicationBootstrap {
  private globalConfigRedisClient: Redis;

  constructor(
    private readonly redisService: RedisService,
    @InjectRepository(GlobalConfigModel)
    private readonly globalConfigModelRepository: Repository<GlobalConfigModel>,
  ) {
    this.globalConfigRedisClient = this.redisService.getClient(
      RedisNamespace.global_config,
    );
  }

  async onApplicationBootstrap(){
    try {
      await this.init();
    }catch (e){}
  }

  private async init(){
    const globalConfigRes = (await this.globalConfigModelRepository.findOne({
      where: { id: 1 },
      select: ['targets', 'sensitive', 'presetSegmentFreq'],
    }))!;

    await this.globalConfigRedisClient.set('', JSON.stringify(globalConfigRes))
  }

  async show() {
    const res: GlobalConfig = JSON.parse((await this.globalConfigRedisClient.get(''))!);
    return {
      targets: res.targets,
      presetSegmentFreq: res.presetSegmentFreq,
    }
  }

  async adminShow() {
    const res: GlobalConfig = JSON.parse((await this.globalConfigRedisClient.get(''))!);
    return  {
      targets: res.targets,
      sensitive: res.sensitive,
      presetSegmentFreq: res.presetSegmentFreq,
    };
  }

  async adminUpdate(
    body: GlobalConfigAdminUpdateDto,
  ): Promise<void> {
    await this.globalConfigModelRepository.update(
      {
        id: 1,
      },
      {
        ...body,
      },
    );
    await this.init();
  }

}
